package com.hamster.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hamster.crm.mapper.UserAndRoleMapper;
import com.hamster.crm.mapper.UserMapper;
import com.hamster.crm.mapper.UserRoleMapper;
import com.hamster.crm.pojo.User;
import com.hamster.crm.pojo.UserRole;
import com.hamster.crm.pojo.dto.UserAndRole;
import com.hamster.crm.service.UserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


/**
 * 用户角色的Service
 * @author Tarry
 * @create 2020/1/2 10:25
 */
@Service
public class UserRoleServiceImpl implements UserRoleService {
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAndRoleMapper userAndRoleMapper;
    /**
     * 新增角色
     * @param userRole
     */
    @Override
    public void insertRole(UserRole userRole) {
        userRoleMapper.insert(userRole);
    }

    /**
     * 获取角色列表
     * @return
     */
    @Override
    public List<UserRole> listRoles() {
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        return userRoleMapper.selectList(userRoleQueryWrapper);
    }

    /**
     * 根据角色 获取user列表
     * @param roleId
     * @return
     */
    @Override
    public List<User> listUserByRole(String roleId) {
       return userMapper.listUserByRole(roleId);
    }

    /**
     * 为角色添加 user
     * @param roleId
     * @param idList
     */
    @Transactional
    @Override
    public void insertRoleUser(String roleId, List<String> idList) {
        //添加多个用户
        for (String id : idList) {
            UserAndRole userAndRole = new UserAndRole();
            userAndRole.setRole_id(roleId);
            userAndRole.setUser_id(id);
            //检查是否存在，不存在则添加
            Integer integer = userAndRoleMapper.checkExistence(roleId, id);
            if (integer == 0){
                userAndRoleMapper.insert(userAndRole);
            }
        }

    }

    /**
     * 删除 指定角色的  指定user
     * @param roleId
     * @param userId
     */
    @Override
    public void deleteRoleUser(String roleId, String userId) {
        QueryWrapper<UserAndRole> userAndRoleEntityWrapper = new QueryWrapper<>();
        userAndRoleEntityWrapper.eq("role_id",roleId);
        userAndRoleEntityWrapper.eq("user_id",userId);
        userAndRoleMapper.delete(userAndRoleEntityWrapper);
    }

    /**
     * 根据id 删除角色，及其权限关系
     * @param roleId
     */
    @Override
    @Transactional
    public void deleteRole(String roleId) {
        //删除角色
        userRoleMapper.deleteById(roleId);
        //删除角色的权限关系
        userRoleMapper.deleteRoleAndPermission(roleId);
        //删除角色相关用户
        userRoleMapper.deleteRoleAndUser(roleId);

    }


}
